﻿
using System.Linq.Expressions;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using PoemGame.Domain.PlayerAggregate;

namespace PoemGame.Repository.MongoDb
{
    public class PlayerRepository:IPlayerRepository
    {

        /// <summary>
        /// 指定的表
        /// </summary>
        const string tbName = "player";

        private readonly IMongoDatabase database;

        public PlayerRepository(IMongoDatabase database)
        {
            this.database = database;
        }

        public async Task<Player?> GetPlayerByUserNameAsync(string username)
        {
            IMongoCollection<Player> colTemp = 
                database.GetCollection<Player>(tbName);
            return await colTemp.Find(o => o.UserName == username)
                .FirstOrDefaultAsync();
        }

        public async Task<Player?> GetPlayerByIdAsync(Guid id)
        {
            IMongoCollection<Player> colTemp = 
                database.GetCollection<Player>(tbName);
            return await colTemp.Find(o => o.Id == id)
                .FirstOrDefaultAsync();
        }

        public async Task<Guid> AddAsync(Player player)
        {
            IMongoCollection<Player> colTemp =
                database.GetCollection<Player>(tbName);

            await colTemp.InsertOneAsync(player);
            return player.Id;
        }

        public async Task RemoveAsync(Player player)
        {
            IMongoCollection<Player> colTemp = 
                database.GetCollection<Player>(tbName);
            await colTemp.DeleteOneAsync<Player>(o => o.Id == player.Id);
        }

        public async Task UpdateAsync(Player player)
        {
            IMongoCollection<Player> colTemp = 
                database.GetCollection<Player>(tbName);
            await colTemp.ReplaceOneAsync<Player>(o => o.Id == player.Id, player);
        }

        public async Task<IEnumerable<Player>> GetAllAsync()
        {
            IMongoCollection<Player> colTemp = 
                database.GetCollection<Player>(tbName);
            return  await colTemp.AsQueryable<Player>().ToListAsync();
        }

        public async Task<IEnumerable<Player>> GetByConditionAsync(
            Expression<Func<Player, bool>> predicate)
        {
            IMongoCollection<Player> colTemp = 
                database.GetCollection<Player>(tbName);
            return  await colTemp.AsQueryable<Player>()
                .Where(predicate).ToListAsync();
        }
    }
}